﻿// ReSharper disable MemberCanBeMadeStatic.Global

namespace KinonekoSoftware.CodariaDB.Documents.Shenanigans
{
    public abstract class CharacterEngine : Engine
    {
        public const string Character_AuthorID = "No.0001";
        public const string Character_AuthorID2 = "No.0002";
        
        public       IEnumerable<Character> GetCharacters()                    => CharacterDB.FindAll();
        public       IEnumerable<Character> GetCharacters(ISet<string> idPool) => CharacterDB.Find(x => !idPool.Contains(x.Id));

        public Character GetCharacter(string id) => CharacterDB.FindById(id);

        public void AddCharacter(Character character)
        {
            if (character is null)
            {
                return;
            }

            if (string.IsNullOrEmpty(character.Id))
            {
                return;
            }

            CharacterDB.Insert(character);
            Modified();
        }

        public void UpdateCharacter(Character character)
        {
            if (character is null)
            {
                return;
            }

            if (string.IsNullOrEmpty(character.Id))
            {
                return;
            }

            CharacterDB.Update(character);
            Modified();
        }

        public void RemoveCharacter(Character character)
        {
            if (character is null)
            {
                return;
            }

            var id = character.Id;

            if (string.IsNullOrEmpty(id))
            {
                return;
            }

            CharacterDB.Delete(id);
            Modified();
        }

        protected override void OnDatabaseOpening(RepositoryOpenContext context)
        {
            var repo          = context.Repository;
            var hasCollection = repo.Has(CollectionNames.CharacterDB);

            CharacterDB = repo.Get<Character>(CollectionNames.CharacterDB);

            //
            // 初始化数据库
            if (!hasCollection)
            {
                OnInitializeDatabase();
            }
        }

        private static void OnInitializeDatabase()
        {
            CharacterDB.Insert(new Character { Id = Character_AuthorID, Name = "作者" });
        }

        protected override void OnDatabaseClosing(ILogger logger)
        {
            CharacterDB = null;
        }


        protected static ILiteCollection<Character> CharacterDB { get; private set; }
    }
}